import axios from "axios";
import { MessageBox } from "element-ui";
import Vue from "vue";

// axios请求封装
const service = axios.create({
    timeout: 9000,
    withCredentials: false
})

// 请求拦截器
service.interceptors.request.use(config =>{
    // 设置请求头
    if(config.url.indexOf("/api/user/login") !== -1){
        config.headers['Content-Type'] = 'multipart/form-data'
    }else{
        config.headers['Content-Type'] = 'application/json'
    }
    // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
    config.headers.token = Vue.ls.get('token')
    return config;
}, error => {
    Promise.error(error)
})

// 响应拦截器
service.interceptors.response.use(response =>{
        if(response.status === 200){
            if(response.data.code === 6000){
                MessageBox.alert(response.data.msg, "系统提示", {
                    confirmButtonText: "确定",
                    callback: () => {
                        localStorage.clear();
                        window.location.href = "/admin/login";
                    }
                }).then(r => {
                    console.log(r)
                });
                return response;
            }else{
                return Promise.resolve(response);
            }
        }else{
            return Promise.reject(response);
        }
    },error =>{
        if(error.response.status === 400){
            MessageBox.alert("Http请求无效！", "系统提示", {
                confirmButtonText: "确定",
                callback: () => {
                    localStorage.clear();
                    window.location.href = "/admin/login";
                }
            }).then(r => {
                console.log(r)
            });
        }else if(error.response.status === 500){
            MessageBox.alert("后台服务未启动，请联系管理员！", "系统提示", {
                confirmButtonText: "确定",
                callback: () => {
                    localStorage.clear();
                    window.location.href = "/admin/login";
                }
            }).then(r => {
                console.log(r)
            });
        }else if(error.response.status === 403){
            MessageBox.alert("该资源未授权！", "系统提示", {
                confirmButtonText: "确定",
                callback: () => {
                    localStorage.clear();
                    window.location.href = "/admin/login";
                }
            }).then(r => {
                console.log(r)
            });
        }else if(error.response.status === 6000){
            MessageBox.alert(error.response.data.msg, "系统提示", {
                confirmButtonText: "确定",
                callback: () => {
                    localStorage.clear();
                    window.location.href = "/admin/login";
                }
            }).then(r => {
                console.log(r)
            });
        }
    }
)

export {service as axios}
